#pragma once
#include <cstdlib>
#include <iostream>
#include <memory>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
#include "logger.hpp"

#include "httplib.h"

namespace bite_im{
class DMSClient {
    public:
        using ptr = std::shared_ptr<DMSClient>;
        DMSClient(const std::string &access_key_id,
            const std::string &access_key_secret) {
            AlibabaCloud::InitializeSdk();
            AlibabaCloud::ClientConfiguration configuration( "cn-chengdu" );
            configuration.setConnectTimeout(1500);
            configuration.setReadTimeout(4000);
            AlibabaCloud::Credentials credential(access_key_id, access_key_secret);
            _client = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);

            _http_client = std::make_unique<httplib::Client>("push.spug.cc");
        }
        ~DMSClient() { AlibabaCloud::ShutdownSdk(); }
        // bool send(const std::string &phone, const std::string &code) {
        //     AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
        //     request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
        //     request.setDomain("dysmsapi.aliyuncs.com");
        //     request.setVersion("2017-05-25");
        //     request.setQueryParameter("Action", "SendSms");
        //     request.setQueryParameter("SignName", "FunChat聊天");
        //     request.setQueryParameter("TemplateCode", "SMS_475245382");
        //     request.setQueryParameter("PhoneNumbers", phone);
        //     std::string param_code = "{\"code\":\"" + code + "\"}";
        //     request.setQueryParameter("TemplateParam", param_code);
        //     auto response = _client->commonResponse(request);
        //     if (!response.isSuccess()) {
        //         LOG_ERROR("短信验证码请求失败：{}", response.error().errorMessage());
        //         return false;
        //     }
        //     return true;
        // }

        bool send(const std::string &phone, const std::string &code){
            std::string path = "/send/d9M8A5yg8KbD?key2=" + code + "&targets=" + phone;

            // 发送 GET 请求
            auto res = _http_client->Get(path.c_str());
            // 检查请求是否成功
            if (!res) {
                LOG_ERROR("短信验证码请求失败:{} ", res.error());
                return false;
            }

            // 检查 HTTP 状态码
            if (res->status != 200) {
                LOG_ERROR("短信验证码请求返回状态异常: {}", res->status);
                return false;
            }

            // 打印响应内容
            LOG_DEBUG("短信验证码请求成功");
            return true;
        }

    private:
        std::unique_ptr<AlibabaCloud::CommonClient> _client;
        std::unique_ptr<httplib::Client> _http_client;
};
}